package so.sao.shop.supplier.kingdee;

import com.github.pagehelper.PageInfo;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import so.sao.shop.supplier.config.CommConstant;
import so.sao.shop.supplier.config.Constant;
import so.sao.shop.supplier.dao.DictItemMapper;
import so.sao.shop.supplier.dao.ParameterDao;
import so.sao.shop.supplier.dao.PurchaseDao;
import so.sao.shop.supplier.dao.SupplierCommodityDao;
import so.sao.shop.supplier.domain.Parameter;
import so.sao.shop.supplier.domain.Purchase;
import so.sao.shop.supplier.kingdee.domain.Item;
import so.sao.shop.supplier.kingdee.parameter.ItemParameter;
import so.sao.shop.supplier.kingdee.parameter.OfflineSendParameter;
import so.sao.shop.supplier.kingdee.parameter.TradeParameter;
import so.sao.shop.supplier.kingdee.domain.Trade;
import so.sao.shop.supplier.kingdee.domain.Items;
import so.sao.shop.supplier.kingdee.domain.Orders;
import so.sao.shop.supplier.kingdee.domain.RTrade;
import so.sao.shop.supplier.kingdee.domain.Trades;
import so.sao.shop.supplier.kingdee.input.ItemParameterInput;
import so.sao.shop.supplier.kingdee.input.TradeParameterInput;
import so.sao.shop.supplier.kingdee.response.ErrorResponse;
import so.sao.shop.supplier.kingdee.response.ItemsGetResponse;
import so.sao.shop.supplier.service.PurchaseService;
import so.sao.shop.supplier.util.BeanMapper;
import so.sao.shop.supplier.util.MD5Util;
import so.sao.shop.supplier.util.Ognl;
import so.sao.shop.supplier.util.PageTool;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;

/**
 * @author gxy on 2017/10/11.
 */
@RestController
@RequestMapping("/kingdee")
public class KingdeeApi {

    @Resource
    private PurchaseService purchaseService;

    @Autowired
    private SupplierCommodityDao supplierCommodityDao;

    @Autowired
    private PurchaseDao purchaseDao;

    @Autowired
    private DictItemMapper DictItemDao;

    @Autowired
    private ParameterDao parameterDao;

    /**
     * 曼柔供应商系统参数key值
     */
    private final String SUPPLIER_KEY = "soft_man_supplier";

    /**
     * 金蝶上架状态
     */
    private final String STATUS_ONSALE = "onsale";

    /**
     * 金蝶下架状态
     */
    private final String STATUS_INSTOCK = "instock";

    @RequestMapping
    public Map<String, Object> execute(HttpServletRequest request, @Valid TradeParameter tradeParameter, ItemParameter itemParameter, OfflineSendParameter offlineSendParameter) throws Exception {
        Map<String, Object> map = new HashMap<>();
        if (isSign(request)){
            switch (request.getParameter("method")) {
                case "kingdee.trades.get" :
                    map = getTrades(tradeParameter);
                    break;
                case "kingdee.items.get" :
                    map = getItems(itemParameter);
                    break;
                case "kingdee.logistics.offline.send" :
                    map = offlineSend(offlineSendParameter);
                    break;
                }
            } else {
                map.put("error_response", ErrorResponse.fail("3", "sign签名错误"));
                return map;
            }
        return map;
    }

    /**
     * 验证签名
     * @param request request
     * @return
     */
    private boolean isSign(HttpServletRequest request) {
        boolean flag = false;
        String signValue = request.getParameter("sign");
        StringBuffer str = new StringBuffer(Constant.SECRET);
        Map<String, String> map = new TreeMap<>();
        Enumeration enu=request.getParameterNames();
        while(enu.hasMoreElements()){
            String paraName=(String)enu.nextElement();
            if (!paraName.equals("sign")) {
                map.put(paraName, request.getParameter(paraName));
            }
        }
        for (Map.Entry<String, String> entry : map.entrySet()) {
            str.append(entry.getKey()+entry.getValue());
        }
        str.append(Constant.SECRET);
        if (signValue.equals(MD5Util.getMD5(str.toString()).toUpperCase())) {
            flag = true;
        }
        return flag;
    }

    /**
     * 获取商品列表Items
     * @param itemParameter
     * @return
     */
    public Map<String, Object> getItems(ItemParameter itemParameter) {
        Map<String, Object> map = new HashMap<>();
        //商品状态转换
        if(null != itemParameter.getStatus()){
            if(itemParameter.getStatus().equals(STATUS_ONSALE)){
                itemParameter.setStatus(CommConstant.COMM_ST_ON_SHELVES + "");
            }
            else if(itemParameter.getStatus().equals(STATUS_INSTOCK)){
                itemParameter.setStatus(CommConstant.COMM_ST_OFF_SHELVES + "");
            }
        }
        //开始分页
        PageTool.startPage(itemParameter.getPage_no(), itemParameter.getPage_size(), CommConstant.PAGE_SIZE_DEFAULT_100);
        //查询曼柔供应商id
        ItemParameterInput itemParameterInput = BeanMapper.map(itemParameter, ItemParameterInput.class);
        List<Parameter> parameterList = parameterDao.selectByKey(SUPPLIER_KEY);
        if(parameterList.size() == 0){
            map.put("error_response", ErrorResponse.fail("0", "未设置曼柔供应商ID系统参数"));
            return map;
        }
        itemParameterInput.setSupplierId(parameterList.get(0).getParameterValue());
        //获取商品列表
        List<Item> itemList = supplierCommodityDao.findItems(itemParameterInput);
        //分页对象
        PageInfo<Item> pageInfo = new PageInfo<>(itemList);
        //商品状态转换
        for(Item item : pageInfo.getList()){
            if(null != item.getApprove_status()){
                if(item.getApprove_status().equals(CommConstant.COMM_ST_ON_SHELVES + "")){
                    item.setApprove_status(STATUS_ONSALE);
                }
                else if(item.getApprove_status().equals(CommConstant.COMM_ST_OFF_SHELVES + "")){
                    item.setApprove_status(STATUS_INSTOCK);
                }
            }
        }
        //拼装返回对象
        Items items = new Items();
        items.setItem(pageInfo.getList());
        ItemsGetResponse itemsGetResponse = new ItemsGetResponse();
        itemsGetResponse.setItems(items);
        itemsGetResponse.setTotal_results(pageInfo.getTotal());
        map.put("items_get_response", itemsGetResponse);
        return map;
    }

    /**
     * 查询卖家已卖出的交易数据
     * @param tradeParameter tradeParameter
     * @return map
     */
    public Map<String, Object> getTrades(TradeParameter tradeParameter) throws Exception {
        Map<String, Object> map = new HashMap<>();
        List<RTrade> rTrades = new ArrayList<>();
        Trades trades = new Trades();
        //开始分页
        PageTool.startPage(tradeParameter.getPage_no(), tradeParameter.getPage_size(), CommConstant.PAGE_SIZE_DEFAULT_100);
        //查询曼柔供应商id
        TradeParameterInput tradeParameterInput = BeanMapper.map(tradeParameter, TradeParameterInput.class);
        List<Parameter> parameterList = parameterDao.selectByKey(SUPPLIER_KEY);
        if(parameterList.size() == 0){
            map.put("error_response", ErrorResponse.fail("0", "未设置曼柔供应商ID系统参数"));
            return map;
        }
        tradeParameterInput.setSupplierId(parameterList.get(0).getParameterValue());
        PageInfo<Trade> dataList = null;
        if (Ognl.isNotNull(tradeParameter.getTid())) {
            //TODO (查看API该字段)订单号有值, 其它业务参数不传值
            tradeParameter.setStart_time(null);
            tradeParameter.setEnd_time(null);
            tradeParameter.setPage_no(null);
            tradeParameter.setPage_size(null);
            tradeParameter.setUse_has_next(false);
            tradeParameter.setStatus(null);
            tradeParameter.setDatatype(null);
            tradeParameter.setFields(null);
        }
        //默认按创建时间
        if(null == tradeParameter.getDatatype()){
            tradeParameter.setDatatype(1);
        }
        if(null != tradeParameter.getStatus()){
            tradeParameter.setStatus(getPurchaseStatus(tradeParameter.getStatus()));
        }
        dataList = purchaseService.getTradeList(tradeParameterInput);
        dataList.getList().forEach(i -> {
            RTrade rtrade = new RTrade();
            rtrade.setTid(i.getTid());
            rtrade.setBuyer_nick(i.getBuyer_nick());
            rtrade.setSeller_nick(i.getSeller_nick());
            rtrade.setPayment(i.getPayment());
            rtrade.setPost_fee(i.getPost_fee());
            rtrade.setReceiver_name(i.getReceiver_name());
            rtrade.setReceiver_state(i.getReceiver_state());
            rtrade.setReceiver_address(i.getReceiver_address());
            rtrade.setReceiver_zip(i.getReceiver_zip());
            rtrade.setReceiver_mobile(i.getReceiver_mobile());
            rtrade.setReceiver_city(i.getReceiver_city());
            rtrade.setReceiver_district(i.getReceiver_district());
            rtrade.setStatus(getKingdeeStatus(i.getStatus()));
            rtrade.setCreated(i.getCreated());
            rtrade.setModified(i.getModified());
            Orders orders = new Orders();
            orders.setOrder(i.getOrders());
            rtrade.setOrders(orders);
            rTrades.add(rtrade);
        });
        trades.setTrade(rTrades);
        Map<String, Object> tradeMap = new HashMap<>();
        if(null == tradeParameter.isUse_has_next() || !tradeParameter.isUse_has_next()){
            tradeMap.put("trades", trades);
            tradeMap.put("total_results", dataList.getTotal());
        }else {
            tradeMap.put("trades", trades);
            tradeMap.put("has_next", dataList.isHasNextPage());
        }
        map.put("trades_get_response",tradeMap);
        return map;
    }

    /**
     * 获取金蝶订单状态
     * @param status
     * @return
     */
    private String getKingdeeStatus(String status){
        //订单状态描述信息
        String description = "";
        switch(status)
        {
            case "1":
                description = "待付款";
                return "TRADE_WAIT_BUYER_PAY";
            case "2":
                description = "待发货";
                return "TRADE_SELLER_SEND_GOODS";
            case "3":
                description = "已发货";
                return "TRADE_WAIT_BUYER_CONFIRM_GOODS";
            case "4":
                description = "已完成";
                return "TRADE_FINISHED";
            case "5":
                description = "已拒收退款审核";
                return "TRADE_WAIT_BUYER_CONFIRM_GOODS";
            case "6":
                description = "已退款";
                return "TRADE_AUTOMATIC_CLOSED";
            case "7":
                description = "已支付退款审核";
                return "TRADE_SELLER_SEND_GOODS";
            case "8":
                description = "待付款已取消";
                return "TRADE_AUTOMATIC_CLOSED";
            case "9":
                description = "退款中";
                return "TRADE_WAIT_BUYER_CONFIRM_GOODS ";
            case "10":
                description = "审核通过";
                return "TRADE_WAIT_BUYER_CONFIRM_GOODS";
            case "11":
                description = "拒绝退款";
                return "TRADE_WAIT_BUYER_CONFIRM_GOODS";
            case "12":
                description = "已收货";
                return "TRADE_FINISHED";
        }
        return "";
    }

    /**
     * 获取订单状态
     * @param status
     * @return
     */
    private String getPurchaseStatus(String status){
        //订单状态描述信息
        String description = "";
        switch(status)
        {
            case "TRADE_WAIT_BUYER_PAY":
                description = "没有付款";
                return "1";
            case "TRADE_SELLER_SEND_GOODS":
                description = "已付款";
                return "2,7";
            case "TRADE_WAIT_BUYER_CONFIRM_GOODS":
                description = "已发货";
                return "3,5,9,10,11";
            case "TRADE_FINISHED":
                description = "交易完成";
                return "4,12";
            case "TRADE_AUTOMATIC_CLOSED":
                description = "交易关闭";
                return "6,8";
        }
        return "";
    }

    /**
     * 物流发货
     * @return
     */
    public Map<String, Object> offlineSend(OfflineSendParameter offlineSendParameter) throws Exception {
        Map<String, Object> map = new HashMap<>();
        if(null == offlineSendParameter.getTid()){
            map.put("error_response", ErrorResponse.fail("0", "交易编号不能为空"));
            return map;
        }
        if(null == offlineSendParameter.getOut_sid()){
            map.put("error_response", ErrorResponse.fail("0", "运单号不能为空"));
            return map;
        }
        if(null == offlineSendParameter.getCompany_code()){
            map.put("error_response", ErrorResponse.fail("0", "物流公司代码不能为空"));
            return map;
        }
        //根据订单编号查询订单信息
        Purchase purchase = purchaseDao.findById(offlineSendParameter.getTid());
        if(null != purchase && purchase.getOrderStatus().equals(Constant.OrderStatusConfig.PENDING_SHIP)){
            //查询物流公司名称
            String companyName = DictItemDao.findNameByCode(offlineSendParameter.getCompany_code());
            if(null == companyName){
                companyName = offlineSendParameter.getCompany_code();
            }
            //物流发货更新订单信息
            purchaseDao.updateOrderInfo(offlineSendParameter.getTid(), offlineSendParameter.getOut_sid(), companyName, new Date());
            map.put("is_success", true);
        }else{
            map.put("is_success", false);
        }
        //拼装返回对象
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("logistics_offline_send_response", map);
        return resultMap;
    }
}
